<!--
 * @Author: wjk
 * @Date: 2020-12-08 15:37:51
 * @LastEditors: wjk
 * @LastEditTime: 2021-01-04 09:52:27
 * @description: file content
-->
<template>
  <base-page-view class-name="page-container material-detail">
    <base-nav :title="''" left-icon="back" background="transparent" title-color="white" :left-click="handleLeftClick">
      <view slot="title" class="material-detail-title">
        {{ isH5 ? '' : articleData.title }}
        <!-- {{ articleData.title }} -->
      </view>
    </base-nav>
    <view class="position-block">
      <swiper class="detail-block" :disable-touch="false" disable-programmatic-animation :current="currentArticle" vertical @transition="verticalChange" @animationfinish="animationfinish" @change="changeCurrentArticle">
        <swiper-item v-for="(keyNum, keyIndex) in viewList" :key="keyIndex">
          <view v-if="keyNum.resource_object_list && keyNum.resource_object_list.length > 0" class="article-resource">
            <view v-if="keyNum.resource_object_list && keyNum.resource_object_list.length > 1" class="resource-nums">{{ (currentIndex + 1 || 1) }}/{{ keyNum.resource_object_list && keyNum.resource_object_list.length }}</view>
            <swiper class="resource-list" circular :current="currentIndex" @change="changeCurrentIndex">
              <swiper-item v-for="(item, index) in keyNum.resource_object_list" :key="index">
                <view class="resource-item">
                  <view v-if="keyNum.type === 8" class="img-box video-box" @click="switchPlay(keyIndex)">
                    <video
                      :id="'videoCtx' + keyIndex"
                      ref="videoCtx"
                      object-fit="contain"
                      :enable-progress-gesture="false"
                      :src="item.resourceUrl"
                      :poster="item.videoPreviewImg"
                      :custom-cache="false"
                      :controls="false"
                      loop
                      @loadedmetadata="videoLoaded(keyIndex)"></video>
                  </view>
                  <view v-else class="img-box" @click="lookDetail(item.resourceUrl)">
                    <image width="750" height="1200" :src="item.resourceUrl" :mode="item.height > 1000 ? 'aspectFill' : 'widthFix'" />
                  </view>
                </view>
              </swiper-item>
            </swiper>
          </view>
        </swiper-item>
      </swiper>
      <view v-if="articleDataLoaded" class="control-block">
        <view class="flex-column-block">
          <view class="column-item user-box">
            <view @click="toUserCenter">
              <b-image class-name="user-portrait" is-head width="70" height="70" :src="articleData.head_img_url" mode="aspectFill" />
            </view>
            <!-- 关注按钮 -->
            <view v-if="!articleData.oneself" class="attention-btn" @click.stop.prevent="attentionOperator">
              <view v-if="articleData.attention_status === 2" class="attention-les">
                <b-image class-name="icon-radius" width="26" height="26" is-asset src="/static/images/material/icon_attention_add.png" mode="aspectFill" />
              </view>
              <view v-else class="attention-les">
                <b-image class-name="icon-radius" width="26" height="26" is-asset src="/static/images/material/icon_attention_ed.png" mode="aspectFill" />
              </view>
            </view>
          </view>
          <view class="column-item zan-button-box">
            <view class="icon-box" @click="praiseOperator">
              <b-image v-if="articleData.is_praise" class-name="icon-radius" width="70" height="70" is-asset src="/static/images/material/icon_material_zan_sel.png" mode="aspectFit" />
              <b-image v-else class-name="icon-radius" width="70" height="70" is-asset src="/static/images/material/icon_material_zan_nor.png" mode="aspectFit" />
            </view>
            <view class="icon-title">{{ articleData.praise_num | formatNumber(2, true) }}</view>
          </view>
          <!-- #ifndef H5 -->
          <view class="column-item ">
            <view class="icon-box" @click="download">
              <b-image class-name="icon-radius" width="70" height="70" is-asset src="/static/images/material/icon_material_download.png" mode="aspectFit" />
            </view>
            <view class="icon-title">{{ articleData.download_num | formatNumber(2, true) }}</view>
          </view>
          <!-- #endif -->
          <view class="column-item ">
            <view class="icon-box" @click="showSharePop">
              <b-image class-name="icon-radius" width="70" height="70" is-asset src="/static/images/material/icon_material_share.png" mode="aspectFit" />
            </view>
            <view class="icon-title">分享</view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部商品 -->
    <footer-bar background="transparent">
      <view class="material-mask-bg">
        <swiper v-if="goodsList && goodsList.length" :current="goodsIndex" class="goodsList-swiper goods-block" autoplay vertical circular next-margin="16rpx" @change="changeGoodsIndex">
          <swiper-item v-for="(item, index) in goodsList" :key="index">
            <view class="sub-item" :class="{'active': goodsIndex === (index - 1) || (goodsList.length > 2 && (index===0 && goodsIndex === goodsList.length -1))}" @click="toGoodsDetail(item)">
              <b-image width="60" height="60" class-name="goods-img" :src="item.goods_image_url" mode="aspectFill" />
              <view class="right-part">
                <view class="goods-name">{{ item.goods_name }}</view>
                <view>
                  <text class="price">{{ item.price | formatMoney }}</text>
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
        <!-- 链接跳转 -->
        <view v-if="linkObj && linkObj.resourceText" class="goodsList-swiper goods-block" @click="toUrl">
          <view class="sub-item">
            <b-image width="60" height="60" class-name="goods-img" :src="linkObj.videoPreviewImg" mode="aspectFill" />
            <view class="right-part">
              <view class="goods-name">{{ linkObj.resourceText }}</view>
            </view>
          </view>
        </view>
        <view class="content-block" @click="showMore">
          <view class="limit-text">
            <block v-if="contentList">
              <view v-for="(item, index) in contentList" :key="index" class="article-line">{{ item }}</view>
            </block>
            <view v-else class="content" v-text="articleData.content"></view>
            <!-- <mole-rich-text :content="articleData.content"></mole-rich-text> -->
          </view>
          <view v-if="contentHeight > 54" class="more">
            更多
            <image src="/static/images/icon/icon_arror_down_white.png" mode="aspectFit" />
          </view>
        </view>
      </view>
    </footer-bar>
    <base-popup :show="pShow" :show-close="false" pop-style="background: rgba(0,0,0,0.8); border-radius: 0" @close="closePopup">
      <view class="material-popup-content-box" @click="closePopup">
        <view class="close-down">
          <b-image width="60" height="26" is-asset class-name="close-down-btn" src="/static/images/material/icon_material_down.png" mode="aspectFill" />
        </view>
        <scroll-view class="material-popup-content" scroll-y>
          <view class="line-box">
            <block v-if="contentList">
              <view v-for="(item, index) in contentList" :key="index" class="article-line">{{ item }}</view>
            </block>
            <view v-else class="content" v-text="articleData.content"></view>
          </view>
        </scroll-view>
        <mole-rich-text v-if="false" :content="articleData.content"></mole-rich-text>
      </view>
    </base-popup>
    <share ref="sharePop" :share-types="[3,5]" :share-option="shareOption" @btnClick="shareBtnClick" />
  </base-page-view>
</template>
<script>

import moleRichText from '@/components/customModules/modules/moleRichText.vue'
import { toGoods, h5NavigateTo } from '@/utils/navigateTo'
import { setClipboardData } from '@/utils/tools'
import footerBar from '@/components/footerBar'
import share from '@/components/draw/share'
import { mapState } from 'vuex'
import './index.scss'
export default {
  name: 'MaterialDetail',
  components: {
    moleRichText,
    footerBar,
    share
  },
  data() {
    return {
      id: '', // 文章ID
      linkObj: {},
      originId: '', // 进入页面的文章id
      pShow: false,
      fromType: '',
      isH5: false,
      currentIndex: 0,
      currentArticle: 0,
      animating: false,
      articleDataLoaded: false,
      goodsIndex: 0,
      cover: '',
      videoObj: {},
      goodsList: [], // 商品素材之商品信息
      randomList: [],
      viewList: [],
      articleData: { // 文章详情
        title: '',
        content: ''
      },
      contentHeight: 20,
      // 分享模块
      assetBg: `${process.env.VUE_APP_IMAGE_ASSET}/images`,
      shareOption: { // 分享自定义设置
        // share_title: '',
        // share_icon: '',
        share_url: '',
        share_list: []
      },
      listLoading: false,
      listMore: true,
      dragDirection: 0
    }
  },
  computed: {
    contentList() {
      if (!this.articleData.content) return ''
      return this.articleData.content.split('\n')
    },
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  async onLoad(options) {
    // #ifdef H5
    this.isH5 = true
    // #endif
    this.id = Number(options.id) || 0
    this.originId = this.id
    this.fromType = options.fromType
    this._initData('init')
    // this.viewList.push(Number(this.id))
    uni.$on('login', () => {
      setTimeout(async() => {
        this.originId = this.id
        this.currentArticle = 0
        this.randomList = []
        this.viewList = []
        this._initData('init')
      }, 50)
    })
  },
  onUnload() {
    uni.$off('login')
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    async _initData(type) {
      if (type === 'init') {
        await this.fetchData(type)
      }

      // 刷新的时候，如果只有一条数据，则只刷新详情
      if (type === 'refresh' && this.viewList.length === 1) {
        await this.fetchData(type)
      } else {
        this.getRandomList(type)
      }
    },
    // 获取详情
    async fetchData(type) {
      const res = await this.$api.materialApi.getMaterialDetail({ id: this.id })
      if (res.success && res.data) {
        this.formatData(res.data, type)
      }
      return res
    },
    formatData(data, type) {
      this.articleDataLoaded = false
      this.articleData = data
      if (type === 'init') {
        this.viewList = []
        this.page_no = 1
        this.viewList.push(this.articleData)
      }
      this.cover = Object.freeze(data.cover)
      this.goodsList = this.articleData.goods || []
      this.goodsIndex = 0
      this.currentIndex = 0
      this.videoContext = null
      if (this.articleData.url_detail && !this.goodsList.length) {
        try {
          const temp = JSON.parse(this.articleData.url_detail)
          if (temp.resourceUrl && temp.resourceText) {
            this.linkObj = { ...temp, isUrl: true }
          } else {
            this.linkObj = { }
          }
          //  else if (temp.goodsUrl && temp.picUrl) {
          //   this.goodsList = [{
          //     id: temp.targetValue,
          //     goods_id: temp.targetValue,
          //     market_price: temp.marketPrice,
          //     goods_name: temp.content,
          //     from_type: temp.fromType,
          //     price: temp.price,
          //     goods_type: temp.goods_type,
          //     pack_type: temp.packType,
          //     goods_image_url: temp.picUrl,
          //     isUrl: true
          //   }]
          // }
        } catch (error) {
          console.log('error', error)
        }
      }
      this.$setNavTitle(this.articleData.title || '详情')
      setTimeout(() => {
        uni.createSelectorQuery().in(this).select('.limit-text').boundingClientRect(data => {
          this.contentHeight = data.height
        }).exec()
        this.initShare()
        this.$forceUpdate()
        uni.stopPullDownRefresh()
      }, 500)
      setTimeout(() => {
        this.articleDataLoaded = true
        // this.initShare() // 解决安卓首次进入详情会有分享的BUG
      }, 50)
      this.initShare()
    },
    // 获取随机详情
    async getRandomList(type) {
      if (!this.page_no) {
        this.page_no = 1
      }
      if (this.listLoading || !this.listMore) return
      this.listLoading = true
      const res = await this.$api.materialApi.getRandomMaterial({
        user_id: this.fromType === 'user-center' ? this.articleData.user_id : '',
        id: this.originId,
        page_no: this.page_no || 1,
        page_size: 10,
        type: this.articleData.type === 8 ? 8 : 2
      })
      this.listLoading = false
      if (res.success && res.data) {
        // if (res.data.length < 10) {
        //   console.log('res.data.length', res.data.length)
        //   return
        // }
        this.listMore = res.data.length === 10
        this.page_no++
        this.randomList = res.data
        if (type === 'init') {
          console.log('init')
        } else if (type === 'refresh') {
          this.viewList = []
        }
        this.viewList = this.viewList.concat(this.randomList)
        if (type === 'refresh' && this.viewList.length) {
          this.formatData(this.viewList[0])
        }
      }
    },
    async attentionOperator() {
      if (!this.token) {
        this.id = this.articleData.id
        this.$navigateTo('/pages/login/index')
        return
      }
      const operatorType = this.articleData.attention_status === 2 ? 1 : 0
      const res = await this.$api.materialApi.attentionOperator({
        operatorType,
        userId: this.articleData.user_id
      })
      if (res.success) {
        this.articleData.attention_status = res.data.attentionStatus
        this.viewList.map(item => {
          if (item.user_id === this.articleData.user_id) {
            item.attention_status = res.data.attentionStatus
          }
        })
        uni.showToast({
          title: this.articleData.attention_status === 2 ? '取消关注成功' : '关注成功',
          icon: 'none',
          duration: 2000
        })
      }
    },
    async praiseOperator() {
      if (!this.token) {
        this.id = this.articleData.id
        this.$navigateTo('/pages/login/index')
        return
      }
      const praise = this.articleData.is_praise ? 0 : 1
      const res = await this.$api.materialApi.praiseOperator({
        praise,
        currentUserId: this.userInfo ? this.userInfo.uid : '',
        id: this.articleData.id,
        praiseNum: this.articleData.praise_num,
        userId: this.articleData.user_id,
        zhongCaoUserId: this.articleData.zhong_cao_user_id
      })
      if (res.success) {
        this.articleData.is_praise = res.data.isPraise
        this.articleData.praise_num = res.data.praiseNum
        uni.showToast({
          title: res.data.isPraise ? '点赞成功' : '取消点赞',
          icon: 'none',
          duration: 2000
        })
      }
    },
    async download() {
      this.$downloadFile(this.articleData.resource_object_list, {
        fileType: this.articleData.type === 8 ? 'Video' : 'Image',
        fileKey: 'resourceUrl',
        callback: (successNum, failNum) => {
          if (successNum > 0) {
            this.operaCount(2)
            this.articleData.download_num++
            uni.showToast({ title: '已保存到本地相册', icon: 'none' })
          }
        }
      })
    },
    verticalChange(e) {
      if (e.detail.dy && Math.abs(e.detail.dy) > 80) {
        this.dragDirection = e.detail.dy
      }
    },
    changeCurrentArticle(e) {
      if (!e.detail) return
      this.animating = true
      if (e.detail.current === this.viewList.length - 1) {
        this.getRandomList()
      }
      if (this.videoContext) {
        this.videoContext.pause()
        this.videoIsPlay = false
      }
      // this.formatData(this.viewList[e.detail.current])
    },
    animationfinish(e) {
      if (this.dragDirection === 0) {
        return
      }
      // debugger
      this.animating = false
      if (e.detail.current === 0 && this.currentArticle === 0 && this.dragDirection && this.dragDirection < 0 && Math.abs(this.dragDirection) > 50) {
        this.page_no = 1
        this.listMore = true
        this._initData('refresh')
        this.dragDirection = 0
        return
      }
      // debugger
      this.currentArticle = e.detail.current
      this.formatData(this.viewList[this.currentArticle])
      this.dragDirection = 0
      // if (e.detail.current === this.viewList.length - 1) {
      //   this.viewList.push(this.randomList.shift())
      // }
      if (this.videoObj && this.videoObj['videoCtx' + this.currentArticle]) {
        this.videoContext = this.videoObj['videoCtx' + this.currentArticle]
        this.videoContext.play()
        this.videoIsPlay = true
      }
    },
    showSharePop() {
      if (this.token) {
        this.operaCount(1)
        this.$refs.sharePop.show(this.shareOption)
      } else {
        this.id = this.articleData.id
        this.$navigateTo('/pages/login/index')
      }
    },
    showMore() {
      if (this.contentHeight > 54) {
        this.pShow = true
      }
      // 复制链接
      if (this.articleData.content) {
        setClipboardData({
          data: this.articleData.content,
          success: () => {
            uni.showToast({
              title: '文案复制成功',
              icon: 'none',
              duration: 1500
            })
            this.operaCount(4)
          }
        })
        return
      }
    },
    async operaCount(countType) {
      // 操作类型：1 ~ 分享统计，2 ~ 下载统计，3 ~ 浏览统计，4 ~ 复制统计,5 ~ 点赞统计
      const res = await this.$api.materialApi.materialCount({
        countType,
        id: this.articleData.id
      })
      if (res.success) {
        if (res.data.countType === 2) {
          this.articleData.download_num = res.data.countNum
        }
        // console.log('res', res)
      }
    },
    closePopup() {
      this.pShow = false
    },
    changeCurrentIndex(e) {
      this.currentIndex = e.detail.current
    },
    changeGoodsIndex(e) {
      this.goodsIndex = e.detail.current
    },
    videoLoaded(index) {
      this.videoObj['videoCtx' + index] = uni.createVideoContext('videoCtx' + index)
      if (index === this.currentArticle) {
        this.videoContext = this.videoObj['videoCtx' + index]
        this.videoContext.play()
        this.videoIsPlay = true
      }
    },
    switchPlay(index) {
      this.videoContext = this.videoObj['videoCtx' + index]
      if (!this.videoContext) {
        return
      }
      if (!this.videoIsPlay) {
        this.videoContext.play()
        this.videoIsPlay = true
      } else {
        this.videoContext.pause()
        this.videoIsPlay = false
      }
    },
    toUserCenter() {
      this.$navigateTo('/pagesMaterial/user-center/index?materialUserId=' + this.articleData.user_id)
    },
    // 分享初始化
    initShare() {
      if (this.token) {
        this.shareOption.share_title = this.articleData.title
        if (this.cover) {
          this.shareOption.share_image = this.cover
        }
        this.shareOption = {
          share_title: this.articleData.title,
          share_content: this.articleData.content,
          share_url: '',
          share_icon: this.cover || '', // 分享图标，路径可以是本地文件路径、代码包文件路径或者网络图片路径、支持PNG及JPG。显示图片长宽比是 5:4
          share_image: this.cover || '',
          share_list: [
            {
              pic: this.cover,
              titleArr: [
                this.articleData.title
              ]
            }
          ]
        }
        if (this.articleData.resource_object_list && this.articleData.resource_object_list.length && this.articleData.type !== 8) {
          this.shareOption.share_list = this.articleData.resource_object_list.map(item => {
            return {
              pic: item.resourceUrl,
              titleArr: [
                this.articleData.title
              ]
            }
          })
        }
        this.showShare()
      } else {
        this.hideShare()
      }
    },
    toGoodsDetail(item) {
      if (item && item.goods_id) {
        toGoods(item)
      }
    },
    toUrl() {
      h5NavigateTo(this.linkObj.resourceUrl)
    },
    handleLeftClick() {
      /* eslint-disable */
      const pages = getCurrentPages()
      /* eslint-disable-end */
      if (pages.length <= 1){
        this.$navigateTo('/pages/moments/index', {}, 'reLaunch')
        return
      }
      uni.navigateBack()
    },
    lookDetail(item) {
      const urls = this.articleData.resource_object_list.map(i => i.resourceUrl)
      uni.previewImage({
        current: item,
        urls: urls
      })
    }
  }
}
</script>
